<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑用户信息' : '新增用户'"
    width="600px"
    class="tech-dialog"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <div class="user-form-container">
      <dv-border-box-13 class="form-box">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
          class="tech-form"
        >
          <el-form-item label="ID" prop="_id" v-if="isEdit">
            <el-input v-model="formData._id" disabled class="tech-input" />
          </el-form-item>

          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="formData.username"
              placeholder="请输入用户名"
              class="tech-input"
              :disabled="isEdit && formData.username === 'admin'"
            />
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
              v-model="formData.password"
              type="password"
              placeholder="请输入密码"
              show-password
              class="tech-input"
            />
          </el-form-item>

          <el-form-item label="创建时间" prop="createTime" v-if="isEdit">
            <el-date-picker
              v-model="formData.createTime"
              type="datetime"
              placeholder="选择日期时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="tech-date-picker"
              :disabled="true"
            />
          </el-form-item>

          <el-form-item label="Token" prop="token" v-if="isEdit">
            <el-input
              v-model="formData.token"
              type="textarea"
              :rows="3"
              placeholder="系统自动生成"
              disabled
              class="tech-input"
            />
          </el-form-item>
        </el-form>
      </dv-border-box-13>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button class="tech-button" @click="dialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          class="tech-button tech-button--primary"
          @click="submitForm"
          :loading="loading"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, nextTick, onMounted } from "vue";
import { ElMessage } from "element-plus";
import cloudbase from "@cloudbase/js-sdk";

export default {
  name: "UserFormDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    userData: {
      type: Object,
      default: () => ({}),
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  emits: ["update:visible", "refresh"],
  setup(props, { emit }) {
    // 初始化 CloudBase
    const app = cloudbase.init({
      env: "your-env-id",
    });

    // 确保身份验证
    onMounted(async () => {
      try {
        const auth = app.auth();
        const loginState = await auth.getLoginState();

        if (!loginState || !loginState.isLoggedIn) {
          await auth.signInAnonymously();
          console.log("匿名登录成功");
        }
      } catch (error) {
        console.error("身份验证失败:", error);
        ElMessage.error("身份验证失败，可能无法保存数据");
      }
    });

    const dialogVisible = ref(props.visible);
    const formRef = ref(null);
    const loading = ref(false);

    // 表单数据
    const formData = reactive({
      _id: "",
      username: "",
      password: "",
      createTime: "",
      token: "",
    });

    // 表单验证规则
    const formRules = reactive({
      username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        {
          min: 3,
          max: 20,
          message: "用户名长度应为3-20个字符",
          trigger: "blur",
        },
        {
          pattern: /^[a-zA-Z0-9_]+$/,
          message: "用户名只能包含字母、数字和下划线",
          trigger: "blur",
        },
      ],
      password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        { min: 6, max: 20, message: "密码长度应为6-20个字符", trigger: "blur" },
      ],
    });

    // 监听visible属性变化
    watch(
      () => props.visible,
      (val) => {
        dialogVisible.value = val;
      }
    );

    // 监听dialogVisible变化，同步回父组件
    watch(dialogVisible, (val) => {
      emit("update:visible", val);
    });

    // 监听userData变化，填充表单
    watch(
      () => props.userData,
      (val) => {
        if (val && Object.keys(val).length > 0) {
          Object.keys(formData).forEach((key) => {
            if (val[key] !== undefined) {
              formData[key] = val[key];
            }
          });
        }
      },
      { immediate: true, deep: true }
    );

    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return;

      await formRef.value.validate(async (valid) => {
        if (!valid) {
          return false;
        }

        loading.value = true;
        try {
          // 确保身份验证
          const auth = app.auth();
          const loginState = await auth.getLoginState();

          if (!loginState || !loginState.isLoggedIn) {
            await auth.signInAnonymously();
            console.log("提交前匿名登录成功");
          }

          // 确定操作类型
          const action = props.isEdit ? "update" : "add";
          const submitData = { ...formData };

          // 调用云函数
          const result = await app.callFunction({
            name: "admin-user-management",
            data: {
              action,
              data: submitData,
            },
          });

          if (result.result.success) {
            ElMessage.success(
              props.isEdit ? "用户信息更新成功" : "用户创建成功"
            );
            dialogVisible.value = false;
            emit("refresh");
          } else {
            ElMessage.error(
              result.result.message || (props.isEdit ? "更新失败" : "创建失败")
            );
          }
        } catch (error) {
          console.error("操作失败:", error);
          ElMessage.error("操作失败: " + (error.message || "网络错误"));
        } finally {
          loading.value = false;
        }
      });
    };

    // 对话框关闭时重置表单
    const handleClosed = () => {
      if (formRef.value) {
        formRef.value.resetFields();
      }

      // 重置表单数据
      Object.keys(formData).forEach((key) => {
        formData[key] = "";
      });
    };

    return {
      dialogVisible,
      formRef,
      formData,
      formRules,
      loading,
      submitForm,
      handleClosed,
    };
  },
};
</script>

<style scoped>
.user-form-container {
  padding: 10px;
}

.form-box {
  padding: 20px;
}

.tech-form {
  color: #ffffff;
}

.tech-form :deep(.el-form-item__label) {
  color: rgba(0, 192, 255, 0.8);
  font-weight: 500;
  text-shadow: 0 0 5px rgba(0, 192, 255, 0.3);
}

.tech-input :deep(.el-input__inner),
.tech-input :deep(.el-textarea__inner) {
  background-color: rgba(0, 30, 60, 0.5);
  border: 1px solid rgba(0, 192, 255, 0.3);
  color: #ffffff;
}

.tech-input :deep(.el-input__inner):focus,
.tech-input :deep(.el-textarea__inner):focus {
  border-color: #00c0ff;
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.5);
}

.tech-input :deep(.el-input__inner:disabled),
.tech-input :deep(.el-textarea__inner:disabled) {
  background-color: rgba(0, 20, 40, 0.7);
  border-color: rgba(0, 192, 255, 0.2);
  color: rgba(255, 255, 255, 0.5);
}

.tech-date-picker {
  width: 100%;
}

.tech-date-picker :deep(.el-input__inner) {
  background-color: rgba(0, 30, 60, 0.5);
  border: 1px solid rgba(0, 192, 255, 0.3);
  color: #ffffff;
}

.tech-date-picker :deep(.el-input__inner:disabled) {
  background-color: rgba(0, 20, 40, 0.7);
  border-color: rgba(0, 192, 255, 0.2);
  color: rgba(255, 255, 255, 0.5);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  background-color: rgba(0, 30, 60, 0.8);
  border-top: 1px solid rgba(0, 192, 255, 0.5);
}

.tech-button {
  background-color: rgba(0, 30, 60, 0.6);
  border: 1px solid rgba(0, 192, 255, 0.5);
  color: #ffffff;
  text-shadow: 0 0 5px rgba(0, 192, 255, 0.5);
}

.tech-button:hover {
  background-color: rgba(0, 192, 255, 0.2);
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.7);
}

.tech-button--primary {
  background-color: rgba(0, 30, 60, 0.6);
  border: 1px solid #00c0ff;
  color: #00c0ff;
  text-shadow: 0 0 5px rgba(0, 192, 255, 0.8);
}

.tech-button--primary:hover {
  background-color: rgba(0, 192, 255, 0.2);
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.7);
}
</style>
